package cn.tedu.jsd2207csmall.passport.config;

import cn.tedu.jsd2207csmall.passport.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public SecurityConfiguration() {
        log.info("创建配置类对象:SecurityConfiguration");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //如果不调用父类方法,默认所有请求都不需要通过认证,可以直接访问
        //super.configure(http);

        //白名单
        String[] urls={
                "/**/*.js",
                "/**/*.css",
                "/doc.html",
                "/swagger-resources",
                "/favicon.ico",
                "/v2/api-docs",
                "/admins/login"
        };

        //启用CorsFilter(Spring Security内置)
        http.cors();

        //将防止伪造跨域攻击的机制禁用
        http.csrf().disable();

        http.authorizeRequests()//管理请求权限
                //.mvcMatchers(HttpMethod.OPTIONS,"/**")
                //.permitAll()

                .mvcMatchers(urls)//匹配某些路径
                .permitAll()//直接许可,即可以不通过认证即可访问
                .anyRequest()//除了以上配置过的的以外,其他所有请求
                .authenticated();//要求是"已经通过认证的"

        //将JWT过滤器添加到Spring Security框架的过滤器链中
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);


        //启用登录表单
        //当未认证时:
        //-- 如果启用了会自动重定向到登录表单
        //-- 如果未启用表单,则会提示403错误
       // http.formLogin();
    }
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;
}
